package com.meiyu.live.ui.mine;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.eventbus.UserInfoUpdateEvent;
import com.meiyu.live.net.param.GetPageParams;
import com.meiyu.live.net.param.IsfocusParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.GetFocusResponse;
import com.meiyu.live.popj.FollowInfo;
import com.meiyu.live.util.RippleUtils;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.UserInfoDialog;

import de.greenrobot.event.EventBus;

/**
 * 我的关注
 */
public class MyFollowActivity extends BaseActivity implements View.OnClickListener {


    private LayoutInflater inflater;
    private MSGView msgView;
    private SwipeRefreshLayout refreshLayout;
    private ListView listView;
    private DataListAdapter adapter;
    private View btn_back, footerView;
    private UserInfoDialog userInfoDialog;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private static final int PAGE_SIZE = 12;
    private int index = 1;
    private boolean hasMore = true;
    private GetFocusResponse getFocusResponse = new GetFocusResponse();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myfollow);
        init();
    }

    protected void init() {
        inflater = LayoutInflater.from(this);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        msgView = (MSGView) findViewById(R.id.msgView);

        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        listView = (ListView) findViewById(R.id.listview);

        footerView = inflater.inflate(R.layout.view_loadmore, null);
        listView.addFooterView(footerView);
        footerView.setVisibility(View.GONE);

        adapter = new DataListAdapter();
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { // 判断滚动到底部
                    if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1) && hasMore) {
                        footerView.setVisibility(View.VISIBLE);
                        getData(false);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        getData(true);
    }

    private void getData(final boolean reload) {
        msgView.showLoading();
        //热门直播接口
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int area[] = {PAGE_SIZE, index + PAGE_SIZE - 1};
        GetPageParams gp = new GetPageParams(area);
        gp.setUrl(Constant.UrlParams.PRIVATEFOCUS);
        request(gp, GetFocusResponse.class, new Response.Listener<GetFocusResponse>() {
            @Override
            public void onResponse(GetFocusResponse getFocusResponse) {
                refreshLayout.setRefreshing(false);
                footerView.setVisibility(View.GONE);
                if (getFocusResponse != null) {
                    if (reload) {
                        MyFollowActivity.this.getFocusResponse.getHash().clear();
                    }
                    MyFollowActivity.this.getFocusResponse.getHash().addAll(getFocusResponse.getHash());
                    index += PAGE_SIZE;
                    if (getFocusResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (getFocusResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            EventBus.getDefault().post(new UserInfoUpdateEvent());
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onError() {
        super.onError();
        refreshLayout.setRefreshing(false);
        footerView.setVisibility(View.GONE);
        msgView.show_error();
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            finish();
            EventBus.getDefault().post(new UserInfoUpdateEvent());
        }
    }

    class DataListAdapter extends BaseAdapter {

        private class ViewHolder {
            View layout_root;
            ImageView iv_avatar, isfollow, status;
            TextView tv_name, tv_level, tv_signature;
        }

        int mainColor = getResources().getColor(R.color.main_theme_color);

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final FollowInfo bean = getFocusResponse.getHash().get(index);
                String id = bean.getUser_id() + "";
                userInfoDialog = new UserInfoDialog(MyFollowActivity.this);
                userInfoDialog.setUserId(id);
                userInfoDialog.show();
            }
        };

        @Override
        public int getCount() {
            return getFocusResponse != null && getFocusResponse.getHash() != null ? getFocusResponse.getHash().size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_follows, null);
                holder = new ViewHolder();
                holder.layout_root = convertView.findViewById(R.id.layout_root);
                RippleUtils.setRippleDrawable(holder.layout_root, mainColor);
                holder.layout_root.setOnClickListener(onItemClickListener);
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_level = (TextView) convertView.findViewById(R.id.tv_level);
                holder.tv_signature = (TextView) convertView.findViewById(R.id.tv_signature);
                holder.isfollow = (ImageView) convertView.findViewById(R.id.isfollow);
                holder.isfollow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        int a[] = {0, 0};
                        request(new IsfocusParams(getFocusResponse.getHash().get((int) v.getTag()).getUser_id(), a),
                                BaseResponse.class,
                                new Response.Listener<BaseResponse>() {
                                    @Override
                                    public void onResponse(BaseResponse onlyStatusResponse) {
                                        if (onlyStatusResponse.getStatusCode() == 6) {
                                            getFocusResponse.getHash().remove((int) v.getTag());
                                            notifyDataSetChanged();
                                        } else {
                                            ToastUtil.show("取消失败，请稍后再试");
                                        }
                                    }
                                });
                    }
                });
                holder.status = (ImageView) convertView.findViewById(R.id.status);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.layout_root.setTag(position);
            final FollowInfo bean = getFocusResponse.getHash().get(position);
            imageLoader.displayImage(bean.getAvatar(), holder.iv_avatar, options);
            holder.tv_name.setText(bean.getName());
            String level = bean.getLevel();
            holder.tv_level.setText(TextUtils.isEmpty(level) ? "1" : level);
            if (TextUtils.isEmpty(bean.getSignature())) {
                holder.tv_signature.setText("暂无介绍");
            } else {
                holder.tv_signature.setText(bean.getSignature());
            }
            switch (bean.getStatus()) {
                case 1:
                    holder.status.setImageResource(R.drawable.wu);
                    break;
                case 2:
                    holder.status.setImageResource(R.drawable.shen);
                    break;
                case 3:
                    holder.status.setImageResource(R.drawable.yue);
                    break;
                case 4:
                    holder.status.setImageResource(R.drawable.ji);
                    break;
                case 5:
                    holder.status.setImageResource(R.drawable.bo);
                    break;
                case 6:
                    holder.status.setImageResource(R.drawable.chi);
                    break;
            }

            holder.isfollow.setTag(position);

            return convertView;
        }
    }
}
